#!/usr/bin/env python
#coding=utf-8

#This file for XCMD, created by OpenThings.
#Using this to automate the test procedure.
#Author: openthings@163.com. copyright&GPL V2.
#Last modified 2014-11-03.

print("  ==================================================")
print("  * X   X            CCCC   M     M  DDDDDD        *")
print("  *  X X            C       MM   MM   D    D       *")
print("  *   X   >>>>>>>>  C       M M M M   D    D       *")
print("  *  X X            C       M  M  M   D    D       *")
print("  * X   X            CCCC   M     M  DDDDDD        *")
print("  *------------------------------------------------*")
print("  *    Welcome to xConsole--[UDP] via WiFi!        *")
print("  *      For XCMD based ESP8266 SoC.               *")
print("  *     By openthings@163.com. 2014-10.            *")
print("  *------------------------------------------------*")
print("  *     通过网络控制台，远程执行@CMD指令集。       *")
print("  ==================================================")

#============================================
import threading
from socket import *
from time import ctime

import xcmd.xc_help

#HOST = '192.168.199.179'
#HOST = '127.0.0.1'
#HOST = '192.168.1.4'
HOST = '192.168.199.227'
PORT = 8266 
ADDR = (HOST, PORT) 
addr = (HOST, PORT) 
IS_RUN = 1

print "   Create Client to UDP server..."
udpClientSock = socket(AF_INET,SOCK_DGRAM)

print "   Using UDP at: HOST-",HOST,",PORT-",PORT
print("   \"$\" for HOST, \"@\" for REMOTE,\"EXIT\" for exit. ")
print("  *================================================*")

#============================================
def udpclient():
	global addr
	while True: 
		if IS_RUN == 0:
			break
		data,addr = udpClientSock.recvfrom(1024)
		if not data: 
		    break 
		print addr,">>",data

def udpstart():
	t_asocket = threading.Thread(target=udpclient,args=())
	t_asocket.setDaemon(True)
	t_asocket.start()

#============================================
def exeCMD(strCMD):
	if (strCMD.find("$")==0):	#主机命令。
		strResult = exeHost(strCMD)
		return strResult
	elif(strCMD.find("?")==0):	#主机命令。
		exeHost_help(strCMD)
	else:
		udpClientSock.sendto(strCMD,ADDR)	#发送到网络。
		#strResult = udpClientSock.sendto(strCMD,ADDR)
		#return strResult

#执行主机的操作。
def exeHost(strCMD):
	print "Host CMD: ",strCMD
	return "Local:",strCMD

def exeHost_help(strCMD):
	xcmd.xc_help.xcmd_list()

#============================================
def waitinput():
	while True: 
		xcmd = raw_input('') 
		if (xcmd.upper()=="EXIT"):
			IS_RUN = 0
			udpClientSock.close()
			print "[xconsole for UART] exited."
			exit()
		exeCMD(xcmd)

#============================================
if __name__ == "__main__":
	udpstart()
	waitinput()

		

